package at.ac.tuwien.dse.health.event.listener;

import at.ac.tuwien.dse.health.event.bus.EventTarget;
import at.ac.tuwien.dse.health.event.type.Event;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.util.Collection;

/**
 * Notifies multiple {@link EventListener EventHandlers} about received {@link Event Events}.
 *
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class ChainEventListener implements EventListener {
	private static final Logger LOGGER = LogManager.getLogger(ChainEventListener.class);
	protected Collection<EventListener> eventListeners;

	public ChainEventListener() {
	}

	@Override
	public void handleEvent(EventTarget eventTarget, Event<? extends Serializable> event) {
		for (EventListener eventListener : eventListeners) {
			try {
				eventListener.handleEvent(eventTarget, event);
			} catch (Throwable t) {
				LOGGER.catching(t);
			}
		}
	}

	/**
	 * Registers the given {@link EventListener}.
	 *
	 * @param eventListener the event listener to register
	 */
	public void addEventListener(EventListener eventListener) {
		eventListeners.add(eventListener);
	}

	public void setEventListeners(EventListener... eventListeners) {
		this.eventListeners = Lists.newArrayList(Preconditions.checkNotNull(eventListeners, "'eventListeners' must not be null"));
	}
}
